package models

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego"
	"mailsrv/utils"
)

//发送邮件管理
type MailerSrv struct {
	Id              int64 `json:"id"`
	Name string `json:"name"`
	Mail_host string `json:"mail_host"`
	Mail_port int `json:"mail_port"`
	Mail_secure string `json:"mail_secure"`
	Account string `json:"account"`
	Password string `json:"password"`
	Desc string `json:"desc"`
	BaseTable
}

func (a *MailerSrv) TableName() string {
	return TableMap["mailsrv"]
}

//获取分页数据
func (mailsrv *MailerSrv) PageList(pagenum int) ([]*MailerSrv, int64) {
	pagesize, _ := beego.AppConfig.Int("PageSize")
	query := orm.NewOrm().QueryTable(mailsrv.TableName())
	data := make([]*MailerSrv, 0)
	limit := (pagenum-1)*pagesize
	total, _ := query.Count()
	query.OrderBy("-Id").Limit(pagesize, limit).All(&data)
	return data, total
}

//获取所有all
func (mailsrv *MailerSrv) AllMails() ([]*MailerSrv) {
	query, _ := orm.NewQueryBuilder("mysql")
	query.Select("id","name","account").
		From(mailsrv.TableName()).
		Where("1 = ?")

	// 导出 SQL 语句
	sql := query.String()

	// 执行 SQL 语句
	data := make([]*MailerSrv, 0)
	o := orm.NewOrm()
	o.Raw(sql, 1).QueryRows(&data)
	return data
}


//通过ID获取记录
func (mailsrv *MailerSrv) GetOne(id int)  (*MailerSrv, error){
	o := orm.NewOrm()
	where := MailerSrv{}
	qs := o.QueryTable(where.TableName())
	err := qs.Filter("id", id).One(&where)

	where.Password = ""
	if err != nil {
		return nil, err
	}
	return &where, nil
}

//通过ID查询完整信息
func (mailsrv *MailerSrv) GetFullOne(id int)  (*MailerSrv, error){
	o := orm.NewOrm()
	where := MailerSrv{}
	qs := o.QueryTable(where.TableName())
	err := qs.Filter("id", id).One(&where)

	if err != nil {
		return nil, err
	}
	return &where, nil
}



//添加项目
func (mailsrv *MailerSrv) MailInsert() error {
	o := orm.NewOrm()
	mailsrv.BaseTable.Created_at = utils.GetNowTime()
	mailsrv.BaseTable.Updated_at = utils.GetNowTime()


	// 插入数据
	_, err := o.Insert(mailsrv)
	if err != nil {
		return err
	}
	return nil
}

//编辑项目
func (mailsrv *MailerSrv) MailEdit() (int64, error) {
	o := orm.NewOrm()
	mailsrv.BaseTable.Updated_at = utils.GetNowTime()

	field := []string{
		"Id",
		"Name",
		"Mail_host",
		"Mail_port",
		"Mail_secure",
		"Account",
		"Desc",
		"Updated_at",
	}
	if mailsrv.Password != ""{
		field = append(field,"Password")
	}


	if num, err := o.Update(mailsrv, field... ); err == nil {
		return num, err
	}else{
		return 0, err
	}
}

//删除机器
func (mailsrv *MailerSrv) MailSrvDel(id int64)(int64, error){
	o := orm.NewOrm()
	mailsrv.Id = id
	if num, err := o.Delete(mailsrv); err == nil {
		return num, err
	}else{
		return 0, err
	}
}